<template>
  <div style="width: 100%; height: 100%;position: relative;">
    <div style="width: 100%; height: 100%" id="chart" ref="chart"></div>
    <div class="legend-container">
        <!-- 展示 tasktype title-->
         <div style="display: flex;flex-direction: column; justify-content: space-between; align-items: center;color: #fff;">
          <span>任务类型：{{ tasktype }}</span>
          <span>状态：{{ title }}</span>
         </div>
      </div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  data() {
    return {
      userData: {},
      chartInstance: null,
    };
  },
  props: {
      tasktype: {
        type: String,
        required: false
      },
      title: {
        type: String,
        required: false
      }
    },
  mounted() {
    // this.initData();
  },
  methods: {
    initData(data,idd) {
      this.userData = data;
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
      this.chartInstance = echarts.init(this.$refs.chart);
      this.getChartOption(idd);
      //   this.chartInstance.setOption(option);
    },
    getChartOption(idd) {
      // 处理节点和关系数据
      console.log("this.userData", this.userData);
      const { nodes, links } = this.processData(this.userData.data,idd);
      console.log("nodes, links", nodes, links);
      const option = {
        title: {},
        tooltip: {
          formatter: function (params) {
            if (params.dataType === "node") {
              return `
                    <div style="text-align:center; padding: 5px;">
                     <img src="${
                       params.data.avatar
                     }" style="width:60px;height:60px;border-radius:50%;border:2px solid #fff;box-shadow:0 0 10px rgba(0,0,0,0.1)"/><br/>
                      <b>${params.data.name}</b><br/>
                      ID: ${params.data.id}<br/>
                      ${
                        params.data.platform
                          ? "平台: " + params.data.platform
                          : ""
                      }
                    </div>
                  `;
            }
            return "";
          },
        },
        animationDurationUpdate: 1500,
        animationEasingUpdate: "quinticInOut",
        series: [
          {
            type: "graph",
            layout: "force",
            force: {
              repulsion: 500,
              edgeLength: 150,
            },
            roam: true,
            zoom: 0.3,
            focusNodeAdjacency: true,
            draggable: true,
            data: nodes,
            links: links,
            categories: [
              { name: "中心用户" },
              { name: "微博用户" },
              { name: "知乎用户" },
              { name: "二级关系" },
            ],
            edgeSymbol: ["none", "arrow"],
            edgeSymbolSize: [0, 10],
            label: {
              show: true,
              position: "right",
              formatter: "{b}",
              fontWeight: 'bold'
            },
            lineStyle: {
              color: "source",
              curveness: 0.2,
            },
            emphasis: {
              lineStyle: {
                width: 5,
              },
            },
          },
        ],
      };

      this.chartInstance.setOption(option);

      // 响应窗口大小变化
      window.addEventListener("resize", () => this.chartInstances.resize());
    },
    processData(rootNode,idd) {
      const nodes = [];
      const links = [];
      const processedIds = new Set();
      let iddd = rootNode.userId
      if(!rootNode.userId){
        iddd = idd
      }
      // 添加中心节点
      nodes.push({
        id: iddd,
        name: rootNode.userNickname || rootNode.userName,
        symbolSize: [80, 80],
        symbol: `image://${require("@/assets/images/profile1.jpg")}`,
        symbolKeepAspect: true,
        symbolClip: true,
        itemStyle: { color: "#5470c6" },
        category: 0,
        fixed: true,
        x: this.$refs.chart.offsetWidth / 2,
        y: this.$refs.chart.offsetHeight / 2,
        category: 0,
      });
      processedIds.add(iddd);

      // 递归处理子节点
      const processChildren = (parentNode, children, level) => {
        if (!children) return;

        children.forEach((child) => {
          if (!processedIds.has(child.userId)) {
            nodes.push({
              id: child.userId,
              name: child.userNickname || child.userName,
              avatar: child.avatar,
              category: level,
              symbolSize: level === 1 ? 40 : 20,
              // 为第一层节点添加白色样式
              itemStyle: level === 1 ? { color: '#ffffff' } : undefined,
              label: level === 1 ? {
                color: '#ffffff',
                fontWeight: 'bold'
              } : undefined
            });
            processedIds.add(child.userId);
          }

          // 添加关系
          links.push({
            source: parentNode.userId,
            target: child.userId,
            // 为第一层连接添加白色样式
            lineStyle: level === 1 ? {
              color: '#ffffff',
              width: 2
            } : undefined
          });

          // 递归处理子节点
          if (child.children) {
            processChildren(child, child.children, level + 1);
          }
        });
      };

      // 从根节点开始处理
      processChildren(rootNode, rootNode.children, 1);

      return { nodes, links };
    },
  },
};
</script>

<style scoped>
  .legend-container {
    position: absolute;
    top: 20px;
    left: 20px;
    background-color: rgba(0, 0, 0, 0.6);
    padding: 10px;
    border-radius: 5px;
    z-index: 1000;
  }
  
  .legend-item {
    display: flex;
    align-items: center;
    margin: 5px 0;
  }
  
  .color-box {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    margin-right: 10px;
    border: 1px solid rgba(255, 255, 255, 0.3);
  }
  
  .legend-text {
    color: #fff;
    font-size: 14px;
  }
  </style>
  
